#include "EntityManager.h"

#include "mem.h"

CEntityManager *CEntityManager::_this = NULL;

CEntityManager::CEntityManager()
{
	m_entitySize = 16;
	m_entityCount = 0;
	g_allocv(m_entityList, TEntityRec, m_entitySize);
}

CEntityManager *CEntityManager::getInstance()
{
	if (!_this)
		g_alloc(_this, CEntityManager);

	return _this;
}

void CEntityManager::killInstance()
{
	g_free(_this);
}


CEntityManager::~CEntityManager()
{
	g_freev(m_entityList);
}


void CEntityManager::update()
{
	for (int i=0;i<m_entityCount;i++)
	{
		m_entityList[i].sqFunc_update();
	}
}

void CEntityManager::paint()
{
	for (int i=0;i<m_entityCount;i++)
	{
		m_entityList[i].sqFunc_paint();
	}
}


SQInteger CEntityManager::sq_addEntity(CEntity *entity, HSQUIRRELVM vm)
{
	if (m_entityCount>=m_entitySize)
	{
		TEntityRec *tmp;
		g_allocv(tmp, TEntityRec, m_entitySize*2);
		for (int i=0;i<m_entitySize;i++)
			tmp[i] = m_entityList[i];
		g_freev(m_entityList);
		m_entityList = tmp;
		m_entitySize *= 2;
	}

	m_entityList[m_entityCount].entity = entity;
	StackHandler sh(vm);
	SquirrelObject obj =  sh.GetObjectHandle(2);

	m_entityList[m_entityCount].sqFunc_update = SquirrelFunction<void>(obj, "update");
	m_entityList[m_entityCount].sqFunc_paint = SquirrelFunction<void>(obj, "paint");

	sq_pushinteger(vm, m_entityCount);

	m_entityCount++;
	return 1;
}
